
package com.zcp.wizard;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug.MemoryInfo;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProcessManagerActivity extends ListActivity implements OnClickListener {
    private static final String TAG = "ProcessManagerActivity";

    /** Called when the activity is first created. */

    private static ArrayList<HashMap<String, Object>> data;

    /**
     * 需要清理的进程集合
     */
    private static final HashMap<String, RunningAppProcessInfo> clearMap = new HashMap<String, ActivityManager.RunningAppProcessInfo>();

    private MyAdapter adapter;

    // private Handler handler = new Handler() {
    //
    // @Override
    // public void handleMessage(Message msg) {
    // buildProcessData();
    // adapter.notifyDataSetChanged();
    // }
    //
    // };

    private CheckBox selectAll;

    private Button btnClear;

    @Override
    public void onDestroy() {
        if (data != null) {
            HashMap<String, Object> temp = null;
            for (int i = 0; i < data.size(); i++) {
                temp = data.remove(i);
                temp.clear();
                temp = null;
            }
        }
        data = null;
        adapter = null;
        // if (handler != null) {
        // handler.removeMessages(0);
        // }
        // handler = null;
        selectAll = null;
        super.onDestroy();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.processmanager);
        data = new ArrayList<HashMap<String, Object>>();
        adapter = new MyAdapter(this, data, R.layout.process_item, new String[] {
                "icon", "label"
        }, new int[] {
                R.id.processIcon, R.id.processTitle
        });
        setListAdapter(adapter);
        btnClear = (Button) this.findViewById(R.id.btnClear);
        // handler.sendEmptyMessageDelayed(0, 500);
        btnClear.setOnClickListener(this);
        selectAll = (CheckBox) findViewById(R.id.cbSelectAll);
        selectAll.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                boolean isChecked = selectAll.isChecked();
                if (isChecked) {
                    clearMap.clear();
                    for (HashMap<String, Object> d : data) {
                        RunningAppProcessInfo rap = (RunningAppProcessInfo) d.get("rap");
                        clearMap.put(rap.processName, rap);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    clearMap.clear();
                    adapter.notifyDataSetChanged();
                }
                checkClearButtonEnable();
            }

        });

        selectAll.setChecked(true);

    }

    @Override
    protected void onResume() {
        loading();
        super.onResume();
    }

    private void loading() {
        LoadTask task = new LoadTask(this);
        task.execute(data);
    }

    /**
     * 检查关闭进程的灰化状态
     */
    private void checkClearButtonEnable() {
        if (clearMap.size() > 0) {
            btnClear.setEnabled(true);
        } else {
            btnClear.setEnabled(false);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        super.onListItemClick(l, v, position, id);
        MyAdapter.ViewHolder vh = (MyAdapter.ViewHolder) v.getTag();
        CheckBox checkBox = vh.check;
        checkBox.setChecked(!checkBox.isChecked());
    }

    private void buildProcessData(ArrayList<HashMap<String, Object>> data) {
        if (data == null) {
            data = new ArrayList<HashMap<String, Object>>();
        }
        data.clear();
        clearMap.clear();
        HashMap<String, Object> map;
        ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager pm = getPackageManager();
        List<RunningAppProcessInfo> appProcessInfos = am.getRunningAppProcesses();
        boolean isSys;
        String name;

        for (RunningAppProcessInfo rap : appProcessInfos) {
            name = rap.processName;
            isSys = name.startsWith("com.google.process") //$NON-NLS-1$
                    || name.startsWith("com.android.phone") //$NON-NLS-1$
                    || name.startsWith("android.process") //$NON-NLS-1$
                    || name.startsWith("system") //$NON-NLS-1$
                    || name.startsWith("com.android.inputmethod") //$NON-NLS-1$
                    || name.startsWith("com.android.alarmclock")
                    || name.startsWith("com.zcp.wizard");
            if (isSys) {
                continue;
            }
            ApplicationInfo applicationInfo = null;
            try {
                applicationInfo = pm.getApplicationInfo(name,
                        PackageManager.GET_UNINSTALLED_PACKAGES);
            } catch (NameNotFoundException e) {
                continue;
            }
            map = new HashMap<String, Object>();
            Drawable icon = pm.getApplicationIcon(applicationInfo);
            map.put("icon", icon);
            String label = pm.getApplicationLabel(applicationInfo).toString();
            map.put("label", label);
            MemoryInfo[] memoryInfos = am.getProcessMemoryInfo(new int[] {
                rap.pid
            });
            MemoryInfo memoryInfo = memoryInfos[0];
            float memory = memoryInfo.getTotalPrivateDirty() / 1024f;

            map.put("mem", String.format("%1$.2fMB", memory));
            map.put("rap", rap);
            map.put("pid", Integer.valueOf(rap.pid));
            clearMap.put(name, rap);
            data.add(map);
        }

    }

    class MyAdapter extends SimpleAdapter {
        class ViewHolder {
            ImageView icon;

            TextView label;

            TextView mem;

            CheckBox check;

        }

        private ArrayList<HashMap<String, Object>> data;

        public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource,
                String[] from, int[] to) {
            super(context, data, resource, from, to);
            this.data = (ArrayList<HashMap<String, Object>>) data;
            this.resource = resource;

        }

        int resource;

        HashMap<String, Object> map;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ViewHolder vh = new ViewHolder();
            if (row == null) {
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(resource, parent, false);
            }
            vh.icon = (ImageView) row.findViewById(R.id.processIcon);
            vh.label = (TextView) row.findViewById(R.id.processTitle);
            vh.mem = (TextView) row.findViewById(R.id.processSize);
            map = data.get(position);
            vh.icon.setImageDrawable((Drawable) map.get("icon"));
            vh.label.setText(map.get("label").toString());
            vh.mem.setText(map.get("mem").toString());
            RunningAppProcessInfo rap = (RunningAppProcessInfo) map.get("rap");
            vh.check = (CheckBox) row.findViewById(R.id.checkClear);
            boolean isClear = clearMap.containsKey(rap.processName);
            Log.i(TAG, "getView count:" + clearMap.size());
            Log.i(TAG, "getView name:" + rap.processName);
            vh.check.setTag(rap);
            vh.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    RunningAppProcessInfo rap = (RunningAppProcessInfo) buttonView.getTag();
                    if (isChecked) {
                        if (!clearMap.containsKey(rap.processName)) {
                            clearMap.put(rap.processName, rap);
                        }
                    } else {
                        clearMap.remove(rap.processName);
                    }
                    if (data.size() != clearMap.size()) {
                        selectAll.setChecked(false);
                    } else {
                        selectAll.setChecked(true);
                    }
                    checkClearButtonEnable();
                }
            });

            vh.check.setChecked(isClear);

            row.setTag(vh);
            return row;
        }

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnClear) {

            ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
            boolean change = false;

            for (String key : clearMap.keySet()) {
                RunningAppProcessInfo rap = clearMap.get(key);
                if (rap.pkgList != null) {
                    for (String pkg : rap.pkgList) {
                        if (pkg != null) {
                            am.restartPackage(pkg);
                        }
                    }
                    change = true;
                }
            }
            if (change) {
                loading();
            }

        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.zoomin, R.anim.zoomout); // 此为自定义的动画效果，下面两个为系统的动画效果
    }

    class LoadTask extends AsyncTask<ArrayList<HashMap<String, Object>>, Integer, String> {

        private ProgressDialog dialog;

        private Context mContext;

        public LoadTask(Context context) {
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(mContext, null, getString(R.string.waiting));
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            if ("Success".equals(result)) {
                dialog.dismiss();
                adapter.notifyDataSetChanged();
            }
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(ArrayList<HashMap<String, Object>>... params) {
            ArrayList<HashMap<String, Object>> data = params[0];
            buildProcessData(data);
            return "Success";
        }

    }
}
